<template>
  <div class="refil-card">
    <div v-for="(i, ind) in cradList" :key="ind" v-permission="[90401, ind + 1]" class="refil-card-box" @click="onCrad(i)">
      <h4>{{ i.title }}</h4>
      <p>{{ i.describe }}</p>
      <p v-if="i.introduce">{{ i.introduce }}</p>
    </div>
    <el-dialog
      v-el-drag-dialog
      :title="title"
      :visible.sync="visible"
      width="850px"
      @close="reset"
    >
      <el-form ref="dataForm" class="form" label-position="left" label-width="80px">
        <el-form-item label-width="0" class="block">
          <el-input v-model.trim="temp.param" style="width: 300px;" placeholder="请输入">
            <el-select slot="prepend" v-model="qtype" style="width: 100px;" placeholder="请选择" @change="change">
              <el-option label="客户电话" value="csmPhone" />
              <el-option label="卡检索" value="cardCode" />
              <el-option label="客户编号" value="csmCode" />
            </el-select>
          </el-input>
          <el-button v-if="isBtn" type="primary" style="margin-left: 10px;" @click="sendMessageCode">{{ btnTxt }}</el-button>
        </el-form-item>
        <el-form-item v-if="isCode" label-width="80" label="验证码:">
          <el-input v-model.trim="messageCode" :minlength="6" :maxlength="6" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <el-table
        v-if="qtype === 'csmPhone'"
        :data="tableData"
        style="width: 100%;"
        @row-click="rowClick"
      >
        <el-table-column
          type="index"
          width="50"
        />
        <el-table-column
          prop="cardCode"
          label="充值卡号"
          width="100"
        />
        <el-table-column
          prop="csmCode"
          label="绑定客户编号"
          width="130"
        />
        <el-table-column
          prop="csmName"
          width="200"
          label="绑定客户名称"
        />
        <el-table-column
          prop="csmPhone"
          width="130"
          label="绑定客户电话"
        />
        <el-table-column
          prop="createTime"
          label="开卡时间"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{m}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset">关闭</el-button>
        <el-button type="primary" @click="save">检索</el-button>
      </div>
    </el-dialog>
    <OpenCrad ref="opencrad" />
    <crad-operate ref="cradOperate" />
    <recharge-config-dialog ref="rechargeConfigDialog" />
  </div>
</template>

<script>
  import { SmartReader, FUNCIDS } from './js/interface'
  import { topUpAdministrationCode, topUpAdministrationQuery, topUpAdministrationInfoInfo, selectCsmcardByCsmCode } from '@/api'
  import OpenCrad from './components/OpenCrad'
  import CradOperate from './components/CradOperate'
  import RechargeConfigDialog from './components/RechargeConfigDialog'
  import { parseTime } from '@/utils'
  export default {
    name: 'refil-card',
    components: {
      OpenCrad,
      CradOperate,
      RechargeConfigDialog
    },
    data() {
      return {
        parseTime: parseTime,
        visible: false,
        isCode: false,
        isBtn: false,
        title: '',
        cradType: 0,
        btnTxt: '获取验证码',
        countdown: 60, // 发送验证码时间60秒
        startSendMessageCode: 0, // 初始化为0
        messageCode: '',
        timer: '',
        qtype: 'csmPhone',
        userInfo: {},
        temp: {
          param: ''
        },
        cradList: [
          { title: '开卡', id: 0, describe: '您可以为客户进行开卡操作' },
          { title: '卡信息修改', id: 11, describe: '您可以为客户进行卡信息修改操作' },
          { title: '充值', id: 1, describe: '您可以为充值卡储值任意金额' },
          { title: '激活', id: 2, describe: '您可以使用此功能激活挂失或冻结的充值卡' },
          { title: '挂失/冻结', id: 3, describe: '您可以使用此功能挂失遗失的充值卡或冻结，充值卡，冻结期间充值卡所有功能不可使用' },
          { title: '换卡', id: 4, describe: '您可以使用此功能将旧充值卡更换为新充值卡' },
          { title: '销卡', id: 5, describe: '您可以使用此功能将充值卡注销，注销后该卡号永久作废' },
          { title: '手机号变更', id: 6, describe: '您可以使用此功能对无法通过验证码校验的手机号进行修改，非常规操作，请谨慎' },
          { title: '卡密码修改', id: 7, describe: '您可以使用原密码为充值卡更改新密码' },
          { title: '卡密码重置', id: 8, describe: '您可以使用此功能将充值卡密码直接', introduce: '重置为初始密码：888888' },
          { title: '调账冲正', id: 9, describe: '您可以使用财务权限为充值卡，调整卡内金额，慎重操作' },
          { title: '自动充值', id: 10, describe: '您可以在此调整绑定银行预留信息，完成自动充值入账调整卡内金额，慎重操作' },
          { title: '充值业务配置', id: 12, describe: '您可以对充值业务进行费用设置、校验设置和消费范围设置' }
        ],
        obj: null, // 读卡器函数
        /* 读卡/写卡相关参数*/
        locked: false,
        csmCardRWType: 0, // 0是默认状态 1是读卡状态 2是写卡状态 3是清卡状态
        readClass: 1,
        writeClass: 2,
        hasCard: false,
        isComOpen: false,
        icdev: -1,
        gl_sector: 0, // 扇区 0-15扇区  总共64个扇区
        gl_BinBlock: 1, // 快   0-63 但0不可用,
        gl_wantFunc: 0,
        readerCsmCard: '', // 读卡号
        readerStrCode: '', // 第二扇区随机数
        readerIndex: 1, // 当前读取扇区
        writerCsmCard: '', // 写卡号
        tableData: []
      }
    },
    async mounted() {
      await this.initCardServer()
    },
    methods: {
      onCrad(i) {
        const obj = {
          1: '充值',
          2: '激活',
          3: '冻结',
          4: '换卡',
          5: '销卡',
          6: '保存',
          7: '保存',
          8: '重置',
          9: '调账',
          10: '保存',
          11: '保存'
        }
        this.$refs.cradOperate.btnTxt = obj[i.id]
        switch (i.id) {
        case 0:
          this.$refs.opencrad.open()
          break
        case 1:// 不显示验证码
        case 9:// 不显示验证码
        case 10:// 不显示验证码
          this.$refs.cradOperate.cradType = i.id
          this.$refs.cradOperate.title = i.title
          this.$refs.cradOperate.visible = true
          break
        case 11:
          this.$refs.cradOperate.getTreeData()
          this.$refs.cradOperate.cradType = i.id
          this.$refs.cradOperate.title = i.title
          this.$refs.cradOperate.visible = true
          break
        case 12:
          this.$refs.rechargeConfigDialog.title = i.title
          this.$refs.rechargeConfigDialog.open()
          break
        default:// 显示验证码
          this.$refs.cradOperate.cradType = i.id
          this.$refs.cradOperate.title = i.title
          this.$refs.cradOperate.visible = true
          this.$refs.cradOperate.isCode = true
          this.$refs.cradOperate.isBtn = true
        }
      },
      change(val) {
        if (val === 'csmPhone' || val === 'csmCode') {
          const condition = [1, 9, 10]
          if (condition.includes(this.cradType)) {
            this.isCode = false
            this.isBtn = false
          } else {
            this.isCode = true
            this.isBtn = true
            this.btnTxt = '获取验证码'
          }
        } else {
          this.isCode = false
          this.isBtn = true
          this.btnTxt = '读卡'
        }
      },
      async save() {
        var _this = this
        // 电话校验
        if (_this.qtype === 'csmPhone') {
          if (!_this.temp.param) {
            this.$message({
              type: 'warning',
              message: '请输入电话号码'
            })
            return
          }
          // 需要校验验证码
          if (_this.isCode) {
            // 校验验证码
            if (_this.messageCode === '') {
              _this.$message({
                type: 'warning',
                message: '请输入验证码!'
              })
              return
            }
            if (_this.messageCode.length !== 6) {
              _this.$message({
                type: 'warning',
                message: '验证码为6位!'
              })
              return
            }
          }
          const res = await topUpAdministrationQuery({
            csmPhone: _this.temp.param,
            messageCode: _this.messageCode
          })
          _this.tableData = res.data
          if (res.data.length === 1) {
            _this.userInfo = res.data[0]
            // 根据充值卡状态,找出不支持的操作
            const backInfo = _this.selectCardStatus(_this.userInfo.cardStatus)
            if (!backInfo.status) {
              _this.$message({
                type: 'warning',
                message: `${backInfo.msg}`
              })
            } else {
              // 检索成功------打开别的弹框
              _this.$refs.cradOperate.open({ cardCode: _this.userInfo.cardCode, type: _this.cradType, title: _this.title })
              _this.visible = false
            }
          }
        // 卡号校验
        } else if (_this.qtype === 'csmCode') {
          if (!_this.temp.param) {
            this.$message({
              type: 'warning',
              message: '请输入客户编号'
            })
            return
          }
          // 需要校验验证码
          if (_this.isCode) {
            // 校验验证码
            if (_this.messageCode === '') {
              _this.$message({
                type: 'warning',
                message: '请输入验证码!'
              })
              return
            }
            if (_this.messageCode.length !== 6) {
              _this.$message({
                type: 'warning',
                message: '验证码为6位!'
              })
              return
            }
          }
          const res = await selectCsmcardByCsmCode({
            csmCode: _this.temp.param
          })
          _this.userInfo = res.data
          // 根据充值卡状态,找出不支持的操作
          const backInfo = _this.selectCardStatus(_this.userInfo.cardStatus)
          if (backInfo.status === false) {
            _this.$message({
              type: 'warning',
              message: `${backInfo.msg}`
            })
            return
          }
          // 检索成功------打开别的弹框
          _this.$refs.cradOperate.open({ cardCode: _this.userInfo.cardCode, type: _this.cradType, title: _this.title })
          _this.visible = false
        } else if (_this.qtype === 'cardCode') {
          if (!_this.temp.param) {
            this.$message({
              type: 'warning',
              message: '请输入卡号'
            })
            return
          }
          // 查询充值卡是否存在
          const res = await topUpAdministrationInfoInfo({
            cardCode: _this.temp.param,
            cardStrCode: _this.readerStrCode
          })
          console.log('yyyyyyyyyyy', res)
          _this.userInfo = res.data
          // 根据充值卡状态,找出不支持的操作
          const backInfo = _this.selectCardStatus(_this.userInfo.cardStatus)
          if (backInfo.status === false) {
            _this.$message({
              type: 'warning',
              message: `${backInfo.msg}`
            })
            return
          }
          // 检索成功------打开别的弹框
          _this.$refs.cradOperate.open({ cardCode: _this.userInfo.cardCode, type: this.cradType, title: _this.title })
          _this.visible = false
        }
      },
      rowClick(row) {
        // 根据充值卡状态,找出不支持的操作
        const backInfo = this.selectCardStatus(row.cardStatus)
        if (!backInfo.status) {
          this.$message({
            type: 'warning',
            message: `${backInfo.msg}`
          })
        } else {
          // 检索成功------打开别的弹框
          this.$refs.cradOperate.open({ cardCode: row.cardCode, type: this.cradType, title: this.title })
          this.visible = false
        }
      },
      // 发送验证码
      async sendMessageCode() {
        if (this.qtype === 'cardCode') {
          // 读卡
          this.readCardCode(1)
          return
        }
        if (!this.temp.param) {
          this.$message({
            type: 'warning',
            message: '请输入电话号码'
          })
          return
        }
        if (this.startSendMessageCode === 0) {
          this.startSendMessageCode = 1
          // 发送接口
          const res = await topUpAdministrationCode({
            csmPhone: this.temp.param,
            type: 1
          })
          console.log('成功', res)
          this.timer = setInterval(() => {
            this.settime()
          }, 1000)
        }
      },
      // 初始化读卡器
      initCardServer() {
        var _this = this
        _this.obj = SmartReader.OBJ()
        _this.obj.createSocket()
        _this.obj.onResult(async(rData) => {
          console.log('进入的状态,rData.FunctionID', rData)
          console.log('进入的状态,rData.FunctionID', rData.FunctionID)
          switch (rData.FunctionID) {
          case FUNCIDS._fid_initialcom:
            var rel = Number(rData.RePara_Int)
            if (rel === 0) {
              var hdev = parseInt(rData.RePara_Str)
              if (hdev !== -1) {
                _this.icdev = hdev
                _this.obj.beep(_this.icdev, 10) // do a beep
                _this.isComOpen = true // Set reader link status
                _this.readerCsmCard = ''
                _this.LoadKey() // 验证密码
              } else {
                _this.locked = false
                _this.$message({
                  type: 'warning',
                  message: '打开读卡器失败'
                })
                return
              }
            } else {
              _this.locked = false
              _this.$message({
                type: 'warning',
                message: '打开读卡器失败'
              })
              return
            }
            break
          case FUNCIDS._fid_exit: // 关闭读卡器
            break
          case FUNCIDS._fid_beep: // 峰槽声
            break
          case FUNCIDS._fid_loadKey: // 校验密码
            if (_this.csmCardRWType === 1) { // 说明是读卡状态
              _this.Read()
            } else if (_this.csmCardRWType === 2) { // 写卡充能
              _this.Write()
            } else if (_this.csmCardRWType === 3) { // 清卡功能
              _this.Write()
            }
            break
          case FUNCIDS._fid_findCardStr: // 读取操作进入
            var strcard = rData.RePara_Str
            if (strcard !== '') {
              _this.hasCard = true
              switch (_this.gl_wantFunc) {
              case _this.readClass:
              case _this.writeClass:
                _this.obj.authentication(_this.icdev, 0, _this.gl_sector)
                break
              }
            } else {
              _this.$message({
                type: 'warning',
                message: '充值设备连接异常，请联系管理员'
              })
              _this.locked = false
              _this.CloseCsmcard()
              return
            }
            break
          case FUNCIDS._fid_authenClass: // 读取
            var rel1 = Number(rData.RePara_Int)
            if (rel1 === 0) {
              switch (_this.gl_wantFunc) {
              case _this.readClass: // 读卡号
                // 读取卡号
                if (_this.readerIndex === 1) {
                  _this.obj.read(_this.icdev, _this.gl_BinBlock)
                  // 读取卡第二扇区值
                } else if (_this.readerIndex === 2) {
                  _this.obj.read(_this.icdev, 2)
                }
                break
              case _this.writeClass: // 写卡号
                _this.obj.write(_this.icdev, _this.gl_BinBlock, _this.writerCsmCard)
                break
              }
            } else {
              _this.$message({
                type: 'warning',
                message: '充值设备连接异常，请联系管理员'
              })
              _this.locked = false
              _this.CloseCsmcard()
              return
            }
            break
          case FUNCIDS._fid_readAsStr: // 输出读取的卡号
            var data = rData.RePara_Str
            if (data !== '') {
              // 读取卡号
              if (_this.readerIndex === 1) {
                _this.readerCsmCard = data
                console.log('读取的卡号_this.readerCsmCard', _this.readerCsmCard)
                // 处理卡号
                if (_this.readerCsmCard === '') {
                  _this.$message({
                    type: 'warning',
                    message: '读取卡号失败'
                  })
                  _this.CloseCsmcard()
                  return
                }

                var strArr = _this.readerCsmCard.split('')
                var newCardCode = ''
                for (var x = 0; x < strArr.length; x++) {
                  if (strArr[x] !== 'A') {
                    newCardCode = newCardCode + strArr[x]
                  }
                }

                // 卡号
                _this.readerCsmCard = newCardCode
                _this.CloseCsmcard()
                // 显示读取的卡号
                if (newCardCode === '00000000000000000000000000000000') {
                  _this.$message({
                    type: 'warning',
                    message: '当前卡读取不到卡号,属于空卡'
                  })
                } else {
                  // 卡号
                  _this.temp.param = newCardCode
                  console.log('_this.temp.param', _this.temp.param)
                  // 开始读取第二扇区随机数
                  _this.readCardCode(2)
                }
              } else if (_this.readerIndex === 2) {
                _this.readerStrCode = data
                console.log('第二区_this.readerStrCode', _this.readerStrCode)
                if (_this.readerStrCode === '00000000000000000000000000000000') {
                  _this.readerStrCode = ''
                }
                // 读取完成第二扇区随机数,将readerIndex值设置成默认值
                _this.readerIndex = 1
                _this.CloseCsmcard()
              }
            } else {
              _this.$message({
                type: 'warning',
                message: '充值设备连接异常，请联系管理员'
              })
              _this.locked = false
              _this.CloseCsmcard()
              return
            }
            break
          case FUNCIDS._fid_writeAsStr: // 输出写入的卡号
            var iRet = Number(rData.RePara_Int)
            if (iRet === 0) {
              // 写入卡片成功
              _this.CloseCsmcard()
            } else {
              _this.$message({
                type: 'warning',
                message: '写入卡片失败'
              })
              _this.CloseCsmcard()
              return
            }
            break
          }
        })
      },
      // 读卡
      readCardCode(index) {
        console.log('读卡')
        var _this = this
        var isOpen = _this.obj.isSocketOpen()
        console.log('读卡状态..isOpen', isOpen)
        if (!isOpen) {
          this.$message({
            type: 'warning',
            message: '充值设备连接异常，请联系管理员'
          })
          return
        }

        _this.readerIndex = index
        _this.csmCardRWType = 1// 设置读卡器状态为读卡状态
        _this.OpenCsmcard() // 打开读卡器
      },
      // 打开读卡器
      OpenCsmcard() {
        var _this = this
        try {
          if (_this.isComOpen === false) {
            console.log('打开读卡器', _this.isComOpen)
            _this.obj.initialcom(100, 0)
          }
        } catch (e) {
          alert(e.message)
        }
        return
      },
      // 校验A密码
      LoadKey() {
        var _this = this
        _this.obj.loadkey(_this.icdev, 0, _this.gl_sector, 'FFFFFFFFFFFf') // Load key, 0: keyA, ffffffffffff:key
      },
      // 读卡
      Read() {
        var _this = this
        _this.obj.findcardStr(_this.icdev, 0)// 1);     //1: multy card mode
        _this.gl_wantFunc = _this.readClass
      },
      // 写卡
      Write() {
        var _this = this
        _this.obj.findcardStr(_this.icdev, 0)// 1);     //1: multy card mode
        _this.gl_wantFunc = _this.writeClass
      },
      // 关闭读卡器
      CloseCsmcard() {
        var _this = this
        _this.obj.exit(_this.icdev)
        _this.isComOpen = false // Set unlink status
      },
      // 验证码倒计时
      settime() {
        if (this.countdown === 0) {
          clearInterval(this.timer)
          this.btnTxt = '免费获取验证码'
          this.countdown = 60
          this.startSendMessageCode = 0
          return
        } else {
          this.countdown--
          this.btnTxt = `重新发送${this.countdown}`
        }
      },
      // 根据充值卡状态,找出不支持的操作
      selectCardStatus(cardStatus) {
        var backInfo = {
          status: true
        }
        if (cardStatus === -1) {
          backInfo.status = false
          backInfo.msg = '充值卡已注销，不可操作'
          if (this.cradType === 5) {
            backInfo.msg = '充值卡已注销，不需要再次注销'
          }
          return backInfo
        }

        switch (this.cradType) {
        // 打开充值界面
        case 1:
          if (cardStatus === 3) {
            backInfo.status = false
            backInfo.msg = '充值卡已冻结，请先激活再操作'
            return backInfo
          }
          break
        // 激活
        case 2:
          if (cardStatus === 2) {
            backInfo.status = false
            backInfo.msg = '充值卡已激活，不需要再次激活'
            return backInfo
          }
          break
        // 挂失/冻结
        case 3:
          if (cardStatus === 3) {
            backInfo.status = false
            backInfo.msg = '充值已冻结，不需要再次操作'
            return backInfo
          }
          break
        }
        return backInfo
      },
      reset() {
        clearInterval(this.timer)
        this.visible = false
        this.isCode = false
        this.isBtn = false
        this.messageCode = ''
        this.btnTxt = '获取验证码'
        this.countdown = 60 // 发送验证码时间60秒
        this.startSendMessageCode = 0 // 初始化为0
        this.userInfo = {}
        this.tableData = []
        this.messageCode = ''
        this.temp = {
          param: ''
        }
        this.qtype = 'csmPhone'
        this.cradType = 0
        this.$nextTick(() => {
          this.visible = false
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.refil-card {
  display: flex;
  // justify-content: space-between;
  justify-content: flex-start;
  width: 100%;
  height: 100%;
  margin-left: 10px;
  overflow: auto;
  flex-wrap: wrap;
  .form {
    display: flex;
    flex-wrap: wrap;
    & /deep/ .el-form-item {
      width: 65%;
      padding-right: 10px;
      .el-form-item__content > .el-select {
        width: 100%;
      }
    }
    .block {
      width: 100%;
    }
  }
  &-box {
    width: 278px;
    height: 156px;
    padding: 31px 21px 0 21px;
    margin-right: 21px;
    margin-bottom: 20px;
    font-family: PingFang SC, PingFang SC-Bold;
    font-weight: 700;
    background: #eceef7;
    background-image: url('~@/assets/bg.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    border-radius: 6px;
    h4 {
      padding: 0;
      margin: 0;
      margin-bottom: 12px;
      font-size: 32px;
      color: #333;
    }
    p {
      // display: -webkit-box; // eslint-disable-line
      overflow: hidden;
      font-family: PingFang SC, PingFang SC-Bold;
      font-size: 14px;
      font-weight: 700;
      line-height: 22px;
      color: #666;
      text-overflow: ellipsis;
      // -webkit-box-orient: vertical; // eslint-disable-line
      // -webkit-line-clamp: 2; // eslint-disable-line
    }
  }
  &-box:hover {
    font-family: PingFang SC, PingFang SC-Bold;
    font-size: 32px;
    font-weight: 700;
    cursor: pointer;
    background: #01999f;
    background-image: url('~@/assets/hBg.jpg');
    box-shadow: 0 3px 6px 0 rgba(0, 0, 0, 0.16);
    h4 {
      color: #fff;
    }
    p {
      font-family: PingFang SC, PingFang SC-Bold;
      font-size: 14px;
      font-weight: 700;
      line-height: 22px;
      color: #fff;
    }
  }
  /deep/.el-form-item__content {
    // display: flex;
    // align-items: center;
  }
}
</style>
